/*
 * @Author: zxh
 * @Email: 1271027008@qq.com
 * @Date: 2020-02-24 08:53:28
 * @Descripttion: 有效期管理
 */

import { Component, OnInit } from '@angular/core';
import { EffectiveManageService } from './effective-manage.service'
import { DatePipe } from '@angular/common';
import { NzModalRef, NzModalService } from 'ng-zorro-antd/modal';
import { NzMessageService } from 'ng-zorro-antd/message';
import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-effective-manage',
  templateUrl: './effective-manage.component.html',
  styleUrls: ['./effective-manage.component.scss']
})
export class EffectiveManageComponent implements OnInit {

  constructor(
    private EffectiveManageService: EffectiveManageService,
    private datePipe: DatePipe,
    private NzModalService: NzModalService,
    private fb: FormBuilder,
    private message:NzMessageService
  ) { }

  ngOnInit(): void {
    this.modalDomBox = document.querySelector("#modal_box");
    this.getKFList()
    this.getList()
    this.validateForm = this.fb.group({
      reserveNum: [''],
      reserveReason: ['', [Validators.required]],
      barcodeBatch:['']
    })
  }

  modalDomBox: any

  // search
  dateRange = []
  proCode: string = ''
  proName: string = ''
  selStatus: number = 0
  selWhseArea: string = ''
  selWhse: string = ''

  whseDataList = []
  getKFList() {
    this.EffectiveManageService.getFKList().subscribe(res => {
      this.whseDataList = res
    })
  }
  whseAreaDataList = []
  selectKF(id) {
    this.selWhse = id
    this.selWhseArea = ''
    this.whseDataList.forEach(item => {
      if (item.id == id) {
        this.whseAreaDataList = item.warehouseAreas
      }
    })
    this.getList('search')
  }
  selectKQ(id) {
    this.selWhseArea = id
    this.getList('search')
  }
  statusDataList = [{ id: 0, label: '临期' }, { id: 1, label: '过期' }]
  selectStatus(type) {
    this.selStatus = type
    this.getList('search')
  }

  // 日期选择
  onDateChange(result: Date): void {
    let startTime = this.formatDate(result[0])
    let endTime = this.formatDate(result[1])
    this.dateRange = [startTime + " 00:00:00", endTime + " 23:59:59"]
    if (!startTime) {
      this.dateRange = []
    }
    this.getList('search')
  }
  // 时间格式化
  formatDate(date) {
    return this.datePipe.transform(date, 'yyyy-MM-dd');
  }

  // table
  pageSize: number = 10
  pageIndex: number = 1
  totalSize: number = 0
  listOfData = []
  listOfDisplayData = [];
  clickPage(index) {
    this.pageIndex = index
    this.getList()
  }
  isAllCheckedStatus: boolean = false
  isHalfCheckedStatus: boolean = false
  mapOfCheckedId: { [key: string]: boolean } = {};
  numberOfChecked = 0;
  dataChange($event): void {
    this.listOfDisplayData = $event;
    this.refreshStatus();
  }
  checkAll(value: boolean): void {
    this.listOfDisplayData.forEach(item => (this.mapOfCheckedId[item.id] = value));
    this.refreshStatus();
  }
  refreshStatus(): void {
    this.isAllCheckedStatus = this.listOfDisplayData.every(item => this.mapOfCheckedId[item.id]);
    this.isHalfCheckedStatus =
      this.listOfDisplayData.some(item => this.mapOfCheckedId[item.id]) && !this.isAllCheckedStatus;
    this.numberOfChecked = this.listOfData.filter(item => this.mapOfCheckedId[item.id]).length;
  }

  //提交请验
  subVerify() {
    let checkedList = this.listOfData.filter(item => this.mapOfCheckedId[item.id])
    console.log(checkedList)
    let _data = {
      barcodeBatch:checkedList[0].barcodeBatch,
      id:checkedList[0].id,
      materialId:checkedList[0].materialId,
      type:0
    }
    this.NzModalService.confirm({
      nzTitle: '确定提交请验？',
      nzOnOk: () => {
        this.EffectiveManageService.verify(_data).subscribe(res => {
          this.message.create('success','提交请验成功！')
          this.getList()
        })
      }
    })
  }
  //提交批次预留
  validateForm: FormGroup;
  isVisible = false
  checkedData = {}
  showModal() {
    this.isVisible = true
    let checkedList = this.listOfData.filter(item => this.mapOfCheckedId[item.id])[0]
    // this.checkedData = checkedList
    this.validateForm.patchValue({
      reserveNum: checkedList.weight,
      barcodeBatch: checkedList.id,
      reserveReason:''
    })
  }
  subBatch() {
    for (const i in this.validateForm.controls) {
      this.validateForm.controls[i].markAsDirty();
      this.validateForm.controls[i].updateValueAndValidity();
    }
    if (this.validateForm.status == 'VALID') {
      let _value = this.validateForm.value
      let _data = {
        isReserve:true,
        reserveNum:_value.reserveNum,
        reserveReason:_value.reserveReason,
        stockBatchId: _value.barcodeBatch
      }
      let _newList = []
      _newList.push(_data)
      this.EffectiveManageService.batch(_newList).subscribe(res=>{
        this.isVisible = false
        this.getList()
        this.mapOfCheckedId = {}
      })
    }
  }
  handleCancel() {
    this.isVisible = false
  }
  //获取有效期管理列表
  getList(type?) {
    if (type) {
      this.pageIndex = 1
    }
    let _newData = {}
    let _data = {
      materialCode: this.proCode,
      materialName: this.proName,
      returntype: this.selStatus,
      warehouseId: this.selWhse,
      warehouseAreaId: this.selWhseArea,
      page: this.pageIndex - 1,
      size: this.pageSize
    }
    if (this.dateRange.length != 0) {
      _newData = {
        ..._data,
        dateList: this.dateRange
      }
    } else {
      _newData = _data
    }
    this.EffectiveManageService.getValidityList(_newData).subscribe(res => {
      this.listOfData = res.content
      this.totalSize = res.totalElements
    })
  }

}
